using Microsoft.Win32;
namespace Gl.SettingsManager.Providers.RegistrySettings
{
	internal class RegistryHelper
	{
		public SettingsCollection GetSettings(RegistryKey regKey, string typeName, string contextName)
		{
			SettingsCollection settings = new SettingsCollection(typeName, contextName);
			RegistryKey reg = GetRegistry(typeName + "_" + contextName, regKey);
			foreach (string key in reg.GetValueNames())
				settings.Add(key, reg.GetValue(key).ToString());
			return settings;
		}

		public void SaveSettings(SettingsCollection collection, RegistryKey regKey)
		{
			RegistryKey reg = GetRegistry(collection.TypeName + "_" + collection.ContextName, regKey);
			foreach (Setting set in collection)
			{
				if (reg.GetValue(set.Name)!= null)
					reg.DeleteValue(set.Name);
				reg.SetValue(set.Name, set.Value, RegistryValueKind.String);
			}
		}

		private RegistryKey GetRegistry(string registryKey, RegistryKey root)
		{
			RegistryKey key = root.OpenSubKey(registryKey, true);
			if (key == null)
				key = root.CreateSubKey(registryKey, RegistryKeyPermissionCheck.ReadWriteSubTree);
			return key;
		}
	}
}
